<template>
  <ElDialog v-model="dialogVisible" title="修改密码" width="600">
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="24">
          <ElFormItem label="新密码" prop="password">
            <ElInput v-model="formData.password" placeholder="请输入新密码" clearable />
          </ElFormItem>
        </el-col>
      </el-row>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit" :loading="submitLoading">确认</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    visible: boolean
    userId: number
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'confirm', payload: { id: number; password: string }): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value: boolean) => emit('update:visible', value)
  })

  const formRef = ref<FormInstance>()
  const submitLoading = ref(false)

  const formData = reactive({
    password: ''
  })

  const rules: FormRules = {
    password: [{ required: true, message: '请输入新密码', trigger: ['blur', 'change'] }]
  }

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        formData.password = ''
        nextTick(() => formRef.value?.clearValidate())
      }
    },
    { immediate: true }
  )

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        emit('confirm', { id: props.userId, password: formData.password })
        // 关闭对话框（可根据业务改为由父组件关闭）
        dialogVisible.value = false
        submitLoading.value = false
      }
    })
  }
</script>

<style scoped lang="scss">
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
</style>
